package com.sunchen.asc.auth.component;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.sunchen.asc.service.user.dto.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前登录用户
 */
@Component
public class LoginUserHolder {
    public UserDto getCurrentUser(){
        // TODO: 2020/12/25 获取当前用户，用作数据权限判断 
        //从Header中获取用户信息
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userStr = request.getHeader("user");
        JSONObject userJsonObject = new JSONObject(userStr);
        UserDto userDto = new UserDto();
        userDto.setUserName(userJsonObject.getStr("user_name"));
        userDto.setId(Convert.toLong(userJsonObject.get("id")));
        userDto.setRoles(Convert.toList(String.class,userJsonObject.get("authorities")));
        return userDto;
    }
}
